import React from "react";
import style from "./style.module.scss";
import { Button, Input, Form } from "react-vant";
import { MyNavBar } from "../../../components";
import { useNavigate } from "react-router-dom";
import { encryptedData, publicKey } from "../../../store/user/userSlice";
import { Notify } from "react-vant";
import { putChangePassword } from "../../../api/my";
import { useAppDispatch, useAppSelector } from "../../../store/hooks";
import { userQuit } from "../../../store/user/userSlice";
const Index: React.FC = () => {
  const navigate = useNavigate();
  const userId = useAppSelector((state) => state.user.userInfo.userId);
  const sessionId = useAppSelector((state) => state.user.userInfo.sessionId);
  const [form] = Form.useForm();
  const state = useAppSelector((state) => state.user as any);
  const dispatch = useAppDispatch();
  const onFinish = async ({
    myPassword,
    setNewPassword,
    verifyNewPassword,
  }) => {
    if (myPassword && setNewPassword && verifyNewPassword) {
      if (setNewPassword === verifyNewPassword) {
        const encryptPwd = encryptedData(publicKey, setNewPassword) as string;
        const oldPwd = encryptedData(publicKey, myPassword) as string;
        const { message } = await putChangePassword(
          userId,
          sessionId,
          oldPwd,
          encryptPwd
        );

        if (message === "修改成功") {
          dispatch(userQuit(state));
          navigate("/login");
        }
      } else {
        Notify.show({ type: "danger", message: "两次密码不一致" });
      }
    } else {
      Notify.show({ type: "danger", message: "输入框不能为空" });
    }
  };

  return (
    <div className={style.changePassword}>
      <MyNavBar
        title="修改密码"
        onClickLeft={() => navigate("/set")}
        style={{ backgroundColor: "#fff" }}
      ></MyNavBar>

      <Form
        className={style.form}
        form={form}
        onFinish={onFinish}
        footer={
          <Button round nativeType="submit" type="primary" block>
            提交
          </Button>
        }
      >
        <Form.Item name="myPassword" label="我的密码">
          <Input placeholder="请输入原密码" align="right" type="password" />
        </Form.Item>
        <Form.Item name="setNewPassword" label="设置新密码">
          <Input placeholder="请输入新密码" align="right" type="password" />
        </Form.Item>
        <Form.Item name="verifyNewPassword" label="确认新密码">
          <Input placeholder="请再次输入密码" align="right" type="password" />
        </Form.Item>
      </Form>
    </div>
  );
};

export default Index;
